
<div class="layui-card layadmin-header">
  <div class="layui-breadcrumb" lay-filter="breadcrumb">
    <a lay-href="">主页</a>
    <a><cite>代理管理</cite></a>
    <a><cite>代理列表</cite></a>
  </div>
</div>

<div class="layui-fluid">
  <div class="layui-card">
    <div class="layui-tab layui-tab-brief">
      <ul class="layui-tab-title">
        <li class="layui-this">代理列表</li>
      </ul>
      <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">
          <div class="layui-row">
            <div class="layui-form" style="float:right;">
              <div class="layui-form-item" style="margin:0;">
                <div class="layui-input-inline">
                  <input type="text" name="agentId" id="searchAgentId" placeholder="代理商ID" autocomplete="off" class="layui-input">
                </div>
                <a id="search" class="layui-btn" data-type="reload"><i class="layui-icon layui-icon-search"></i>搜索</a>
              </div>
            </div>
          </div>
          <div class="layui-row">
            <div class="layuiAdmin-btns" style="margin-bottom: 10px;">
              <a class="layui-btn agentAddBtn"><i class="layui-icon layui-icon-add-1"></i>新增</a>
              <a class="layui-btn layui-btn-danger" data-type="del" data-events="del" id="del"><i class="layui-icon layui-icon-delete"></i>彻底删除</a>
            </div>
          </div>
          <table id="XxPay_Mgr_Agent_dataAll" lay-filter="XxPay_Mgr_Agent_dataAll"></table>
          <div class='layui-row layui-fluid'> 统计： 汇总余额 <span style='color:red' id='totalBalacne' ></span> 元。</div>
        </div>

      </div>
    </div>
  </div>
</div>

<script>
  layui.use(['admin', 'table', 'util'], function(){
    var $ = layui.$
            ,admin = layui.admin
            ,table = layui.table
            ,element = layui.element
            ,form = layui.form
            ,view = layui.view;

    element.render('breadcrumb', 'breadcrumb');
    $.setCountResult = function() {
        admin.req({
            type: 'get',
            url: layui.setter.baseUrl + '/agent_account/agent_count',
            data: {},
            error: function(err){
                layer.alert(JSON.stringify(err.field), {
                    title: '错误提示'
                })
            },
            success: function(res){
                if(res.code == 0){
                    // $('#agentTotalCount').html(res.data.agentCount);
                    $('#totalBalacne').html(res.data.balanceCount/100.00);
                }
            }
        });
    };

    var tplStatus = function(d){

        var checkedHtml = " agentId='"+d.agentId+"' ";
        if(d.status == 1) {
            checkedHtml += " checked";
        }
        return '<input type="checkbox" lay-filter="statusSwitch" lay-skin="switch" '+checkedHtml+' lay-text="启用|停用">';
    };

      var tplLevel = function(d){
          if(d.agentLevel == 1) {
              return "总代理";
          }
          return "商户代理";
      };

      var tplParentAgentId = function(d){
          if(d.parentAgentId == 0) {
              return "";
          }
          return d.parentAgentId;
      };

    var tplEdit = function(d){
      return "<a class='layui-btn layui-btn-primary layui-btn-xs' target='_blank' lay-event='loginAgent'><i class='layui-icon layui-icon-auz'></i>登录</a>" +
              "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='infoDetail'><i class='layui-icon layui-icon-about'></i>查看</a>" +
              "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='settConfig'><i class='layui-icon layui-icon-set-fill'></i>结算</a>" +
              "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='passage'><i class='layui-icon layui-icon-template-1'></i>支付</a>" +
              "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='agentpayPassage'><i class='layui-icon layui-icon-template'></i>代付</a>" +
              "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='change'><i class='layui-icon layui-icon-rmb'></i>调额</a>" +
              /*"<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='pwdReset'>重置密码</a>" +*/
              "<a class='layui-btn layui-btn-xs' lay-event='edit'><i class='layui-icon layui-icon-edit'></i>编辑</a>";

    };

    //商户列表
    table.render({
      elem: '#XxPay_Mgr_Agent_dataAll'
      ,url: layui.setter.baseUrl + '/agent_info/list' //列表接口
      ,where: {
          access_token: layui.data(layui.setter.tableName).access_token
      }
      ,id: 'tableReload'
      ,page: true
      ,cols: [[
        {type: 'checkbox', fixed: 'left'}
        ,{field: 'agentId', title: '代理ID'}
        ,{field: 'agentName', title: '代理名称'}
        ,{field: 'agentLevel', title: '代理等级', templet: tplLevel}
        ,{field: 'parentAgentId', title: '总代理ID', templet: tplParentAgentId}
        ,{field: 'agentBalance', title: '余额', templet: function(d){return d.agentBalance / 100;}}
        ,{field: 'status', title: '状态', templet: tplStatus}
        /*,{field: 'createTime', title: '创建时间', width: 200, templet: '<div>{{ layui.util.toDateString(d.createTime, "yyyy-MM-dd HH:mm:ss") }}</div>'}*/
        ,{field: 'edit', title: '操作', width: 460, fixed: 'right', templet: tplEdit }
      ]]
        ,skin: 'line'
        ,done: function () {
            // 初始化统计结果
            $.setCountResult();
        }
    });

    //监听工具条
    table.on('tool(XxPay_Mgr_Agent_dataAll)', function(obj){
      var data = obj.data;
      if(obj.event === 'infoDetail'){
          view.xxpayPopup("查看代理商信息", "agent/list/agent_view", {agentId: data.agentId}, {btn: false});
      } else if(obj.event === 'accountDetail'){
        location.href = layui.setter.baseLocal + "agent/list/account_view/agentId=" + data.agentId;
      } else if(obj.event === 'settConfig'){
          view.xxpayPopup("更改代理商结算设置", "agent/list/agent_sett", {agentId: data.agentId}, {area:['70%','70%']});
      } else if(obj.event === 'passage'){
        location.href = layui.setter.baseLocal + "agent/passage/list/agentId=" + data.agentId;
      } else if(obj.event === 'agentpayPassage'){
        location.href = layui.setter.baseLocal + "agent/agentpay_passage/list/agentId=" + data.agentId;
      } else if(obj.event === 'pwdReset'){
        layer.prompt({
          formType: 1,
          title: '请输入新密码'
        }, function(value, index, elem){
          admin.req({
            type: 'get',
            url: layui.setter.baseUrl + '/agent_info/pwd_reset',
            data: {
              agentId : data.agentId,
              password : value
            },
            error: function(err){
              layer.alert(JSON.stringify(err.field), {
                title: '错误提示'
              })
            },
            success: function(res){
              if(res.code == 0){
                layer.msg('修改成功', {icon: 1});
              }
            }
          });
          layer.close(index);
        });

      }else if(obj.event === 'change'){
          view.xxpayPopup("代理商余额变更", "agent/list/agent_change", {agentId: data.agentId}, {btn: false, area:['40%','80%']});
      }else if(obj.event === 'edit'){
          view.xxpayPopup("编辑代理商信息", "agent/list/agent_edit", {agentId: data.agentId});
      }else if(obj.event === 'loginAgent'){
          admin.req({
              type: 'post',
              url: layui.setter.baseUrl + '/agent_info/genLoginUrl',
              data: {agentId : data.agentId},
              success: function(resData){
                  layer.alert("请点击登录按钮（有效期1分钟）：", {btn:['登录']}
                      ,function(aid){
                          window.open(resData.data.loginUrl);
                          layer.close(aid);
                      });
              }
          });
      }
    });

      // 事件处理
      var events = {
          del: function () { //获取选中数据
              var checkedData = table.checkStatus("tableReload").data; //获得选中的数据
              if (checkedData.length === 0) return layer.msg('请选择数据');
              var delIds = [];
              $.each(checkedData, function () {
                  delIds.push(this.agentId);
              });

              //弹层
              var relationDeleteHtml = `
                <div style="color:red; margin:20px; padding-left:50px" >
                    <label class="layui-inline"> 此操作将删除选中数据及所有关联数据！是否继续删除？</label><br/><br/>
                    <label class="layui-inline"> 关联表：[代理商信息];[代理商账户表];[代理商通道表];</label><br/>
                    <label class="layui-inline"> [代理商代付通道表];[代理商每日结算汇总];</label><br/>
                    <label class="layui-inline"> [代理商资金账户流水表];[结算记录表] 及下级代理商和所有下辖商户</label><br/>
                    <label class="layui-inline"> 所有关联数据！</label>


                </div>
                <form class="layui-form center">
                    <div class="layui-form-item" style="margin-top:20px">
                        <label class="layui-form-label" style="width:130px;">平台超级密码：</label>
                        <div class="layui-input-inline" style="width: 312px;">
                            <input type="password" autocomplete="off" class="layui-input relationDeletePassword">
                        </div>
                    </div>
                    <div class="layui-form-item" style="margin-top:30px">
                        <div class="layui-input-block" style="margin-left: 180px;">
                            <button type="button" class="layui-btn layui-btn-danger relationDeleteBtn">确认删除</button>
                            <button type="button" class="layui-btn layui-btn-normal" onclick="layer.closeAll();">取消</button>
                        </div>
                    </div>
                </form>
            `;
              //打开弹层
              var thisLayerId = layer.open({type: 1, area: ['520px', 'auto'], title: '提示', content: relationDeleteHtml});
              $(".relationDeleteBtn").click(function () {
                  var relationDeletePassword = $('.relationDeletePassword').val();
                  if(!relationDeletePassword) return layer.msg('请输入平台超级密码！');

                  var layerMsgId = layer.msg('正在执行删除任务... ', {time: 0, shade: 0.3});
                  admin.req({
                      type: 'get',
                      url: layui.setter.baseUrl + '/agent_info/relationDelete',
                      data: {ids: JSON.stringify(delIds), superPassword: relationDeletePassword},
                      error: function (err) {
                          layer.close(layerMsgId);
                          layer.alert(err);
                      },
                      success: function (res) {
                          layer.close(layerMsgId);
                          if (res.code == '0') { //成功创建任务
                              layer.close(thisLayerId);
                              table.reload('tableReload');  //刷新页面
                              layer.alert("操作成功, 共删除了 "+res.data+" 条关联数据！");
                          }
                      },
                      complete: function(){
                          layer.close(layerMsgId);
                      }
                  });
              });
          }

      };

      $('.layuiAdmin-btns .layui-btn').on('click', function(){
          var othis = $(this)
              ,thisEvent = othis.data('events')
              ,type = othis.data('type');
          events[thisEvent] && events[thisEvent].call(this, othis, type);
      });


    // 搜索
    var $ = layui.$, active = {
      reload: function(){
        var agentId = $('#searchAgentId').val();
        //执行重载
        table.reload('tableReload', {
          page: {
            curr: 1 //重新从第 1 页开始
          }
          ,where: {
            agentId: agentId
          }
        });
      }
    };

    form.on('switch(statusSwitch)', function(data){

        var agentId = $(data.elem).attr('agentId');
        var updateState = data.elem.checked ? "1" : "0";
        var loadingIndex = layer.load();
        admin.req({
            type: "POST",
            url: layui.setter.baseUrl + '/agent_info/update',
            data: {agentId: agentId, status: updateState},
            success: function(res){
                if(res.code == 0) {
                    table.reload('tableReload');
                }
            },
            complete:function(){
                layer.close(loadingIndex);
            }
        });
    });

    $('#search').on('click', function() {
      var type = $(this).data('type');
      active[type] ? active[type].call(this) : '';
    });

    $(".agentAddBtn").click(function(){
        view.xxpayPopup("新增代理商", "agent/list/agent_add");
    });

    // 渲染表单
    form.render();
  });
</script>